import { useVModel, useVModels } from "@vueuse/core";
import {
    Modal,
    InputNumber,
    Divider,
    CheckboxGroup,
    Row,
    Checkbox,
    Col,
    Select,
    RadioGroup,
    Space,
    Input,
    SelectOption,
    Menu,
    MenuItem,
    Dropdown,
    Button,
    AutoComplete,
    Cascader,
    Switch,
    TreeSelect,
    Radio,
    TypographyParagraph,
    Form,
    Textarea
} from "ant-design-vue";
import { useCityOptions, useYunSonTypeOptions, useGetWebsiteDomains, type CityOptions, type FieldOptionsObjType } from "@/hooks/main/useWebsites";
import {
    keywordRankingAnalysisApi,
    customWebsiteAndCityRootKwdAnalysisApi,
    websiteInfoAnalysisApi,
    GenerateTargetKeywordsApi,
    getKeywordUseCategorysApi,
    keywordRankingTaskRedisKeysApi,
    keywordRankingAnalysisUpsAndDownsApi,
    WebsiteRankingAnalysisReportApi,
    keywordThesaurusApi,
    webrankContinuedDownOrUpAnalysisApi,
    singleWebRankingkeywordAnalysisUpsAndDownsApi
} from "@/api/keyword";
import { message } from "ant-design-vue";
import { DownOutlined, MinusCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
import {  getDestoonCategoryApi, pushWebsiteLinkApi, websiteLinkCheckApi } from "@/api/friendlyChain";
import mainStore from "@/stores/main";
import { esCommonActionApi, getDomainSelectInfoApi } from "@/api/esArticle";
import { filterOption } from "@/hooks/useCommon";
import { useAdOptions, useVarOptions } from "@/hooks/advertising/useAdvertising";
import { useCommonStaticOptions } from "@/hooks/useEsArticleCommon";
import { websiteAndAdApi } from "@/api/advertisingSystem";
import { useVarValueOptions } from "@/hooks/advertising/useVarValue";
import { getWebsiteTplListApi, updateWebsiteTplApi } from "@/api";
import { addWebsiteDynamicAdApi, webBindSecurityConfigApi, websiteDynamicOutlinkConfigApi, websitesBulkBindTplWycApi } from "@/api/utils";
import { useWebSecurityConfigOptions } from "@/hooks/utils/webSecurity/useWebSecurityConfigs";
import { useWebLinkRuleOptions } from "@/hooks/utils/dynamicLink/useLinkRule";
import { useDomainSelectData } from "@/assets/ts/websitesTableColumns";
import { toUrl } from "@/utils/common";
import { getNginxRuleApi, getWebProgramsApi, updateWebProgramIdApi, updateWebsiteNginxRuleIdApi } from "@/api/yunwei";
const $store = mainStore();
export const KeywordRankingAnalysisComponent = defineComponent({
    props: ["visible", "type", "selectedRowKeys"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; type: number; selectedRowKeys: Array<Record<string, number>> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const lastNum = ref(4);
        const cityOptions = ref<Array<CityOptions>>([]);
        const cityCores = ref<Array<number>>([1]);
        // 收集选择的城市
        const citys = ref<Array<string>>(["武汉", "北京"]);
        const getCityCoresValues = (label: any) => {
            return cityOptions.value.find((item) => item.label == label)?.values;
        };
        // 确定后加载的按钮
        const confirmLoading = ref(false);
        const onOkFunc = () => {
            const obj = { citys: citys.value, type: props.type, last_num: lastNum.value, website_domains: {} };
            obj.website_domains = useGetWebsiteDomains(props.selectedRowKeys);
            confirmLoading.value = true;
            keywordRankingAnalysisApi(obj)
                .then((res) => {
                    if (res.data.code === 200) {
                        message.success("准备下载Excel文件...");
                        if (import.meta.env.DEV) {
                            window.location.href = "http://192.168.1.63:5000" + res.data.csv_file_path;
                        } else {
                            window.location.href = "http://192.168.1.112:5000" + res.data.csv_file_path;
                        }
                    } else {
                        message.error("服务器错误!");
                    }
                })
                .catch((e) => {
                    message.error("服务器错误!");
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        onMounted(() => {
            useCityOptions().then((res) => (cityOptions.value = res));
        });
        return () => (
            <Modal
                v-model:open={visible.value}
                title="选择条件"
                style="width:400px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                最近n次孕站群排名结果：
                <InputNumber placeholder="最近n次孕站群排名结果:" max={8} min={1} v-model:value={lastNum.value}></InputNumber>
                {props.type === 1 ? (
                    <>
                        <Divider>请选择城市:</Divider>
                        <CheckboxGroup v-model:value={cityCores.value} style="width: 100%">
                            <Row>
                                {cityOptions.value.map((item) => {
                                    return (
                                        <Col span={6}>
                                            <Checkbox value={item.label}>{item.label}级城市</Checkbox>
                                        </Col>
                                    );
                                })}
                            </Row>
                        </CheckboxGroup>
                        <CheckboxGroup v-model:value={citys.value} style="width: 100%">
                            {cityCores.value.map((key) => {
                                return (
                                    <>
                                        <Divider>{key}级城市</Divider>
                                        <Row>
                                            {getCityCoresValues(key)?.map((city) => {
                                                return (
                                                    <Col span={6}>
                                                        <Checkbox value={city}>{city}</Checkbox>
                                                    </Col>
                                                );
                                            })}
                                        </Row>
                                    </>
                                );
                            })}
                        </CheckboxGroup>
                    </>
                ) : (
                    <span></span>
                )}
            </Modal>
        );
    }
});
// 网站排名词与关键词分类与根词分析
export const KeywordRankingAndKeytypeAndRootKwdAnalysisComponent = defineComponent({
    props: ["visible", "selectedRowKeys"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; selectedRowKeys: Array<Record<string, number>> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const lastNum = ref(4);
        const cityKeyTypeOptions = ref<SelectOption>([]);
        // 确定后加载的按钮
        const confirmLoading = ref(false);
        const cityKeyType = ref(102);
        const onOkFunc = () => {
            const keytype_option = cityKeyTypeOptions.value.find((item) => item.value === cityKeyType.value) || {
                label: "",
                value: 0
            };
            if (keytype_option.value === 0) {
                return message.error("请选择城市分类!");
            }
            const obj = { keytype_option, last_num: lastNum.value, website_domains: {} };
            obj.website_domains = useGetWebsiteDomains(props.selectedRowKeys);
            confirmLoading.value = true;
            customWebsiteAndCityRootKwdAnalysisApi(obj)
                .then((res) => {
                    if (res.data.code === 200) {
                        message.success("准备下载Excel文件...");
                        if (import.meta.env.DEV) {
                            window.location.href = "http://192.168.1.63:5000" + res.data.csv_file_path;
                        } else {
                            window.location.href = "http://192.168.1.112:5000" + res.data.csv_file_path;
                        }
                    } else {
                        message.error("服务器错误!");
                    }
                })
                .catch((e) => {
                    message.error("服务器错误!");
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        onMounted(() => {
            useYunSonTypeOptions().then((res) => (cityKeyTypeOptions.value = res));
        });
        return () => (
            <Modal
                v-model:open={visible.value}
                title="选择条件"
                style="width:400px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                选择关键词城市分类：
                <Select options={cityKeyTypeOptions.value} v-model:value={cityKeyType.value}></Select>
                <br />
                <br />
                最近n次孕站群排名结果：
                <InputNumber placeholder="最近n次孕站群排名结果:" max={8} min={1} v-model:value={lastNum.value}></InputNumber>
            </Modal>
        );
    }
});
// 网站信息与城市,根词分析
export const WebsiteInfoAndCityAndRootKeywordAnalysisComponent = defineComponent({
    props: ["visible", "selectedRowKeys"],
    setup(props: { visible: boolean; selectedRowKeys: Array<Record<string, number>> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const confirmLoading = ref(false);
        // 确定提交
        const onOkFunc = () => {
            if (!analysisValues.value.length) {
                analysisValues.value = analysisSelectOptions.map((item) => item.value) as Array<string>;
            }
            const webids = props.selectedRowKeys.map((item) => Object.values(item)[0]);
            // 调用接口
            confirmLoading.value = true;
            websiteInfoAnalysisApi({ webids, targets: analysisValues.value, type: analysisTypeValue.value })
                .then((res) => {
                    if (res.data.code === 200) {
                        message.success("准备下载Excel文件...");
                        if (import.meta.env.DEV) {
                            window.location.href = "http://192.168.1.63:5000" + res.data.csv_file_path;
                        } else {
                            window.location.href = "http://192.168.1.112:5000" + res.data.csv_file_path;
                        }
                    } else {
                        message.error("服务器错误!");
                    }
                })
                .catch((e) => {
                    message.error("服务器错误!");
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        // 分析对象
        const analysisSelectOptions: SelectOption = [
            {
                label: "TKD",
                value: "TKD"
            },
            {
                label: "目标关键词",
                value: "target_keywords"
            },
            {
                label: "tag",
                value: "tag"
            },
            {
                label: "文章标题",
                value: "article_title"
            },
            {
                label: "栏目名称",
                value: "column_name"
            }
        ];
        const analysisValues = ref<Array<string>>([]);
        // 分析类型
        const analysisTypeSelectOptions: SelectOption = [
            {
                label: "城市",
                value: "city"
            },
            {
                label: "内容根词",
                value: "root_keyword"
            }
        ];
        const analysisTypeValue = ref("city");
        return () => (
            <Modal
                v-model:open={visible.value}
                title="选择条件"
                style="width:400px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                <span>选择分析对象：</span>
                <CheckboxGroup v-model:value={analysisValues.value} name="checkboxgroup" options={analysisSelectOptions} />
                <br />
                <br />
                选择分析模式：
                <a-radio-group v-model:value={analysisTypeValue.value} options={analysisTypeSelectOptions} />
            </Modal>
        );
    }
});

// 网站分析(获取目标关键词)
export const WebsiteInfoAnalysisGetTargetKeywordComponent = defineComponent({
    props: ["visible", "selectedRowKeys"],
    setup(props: { visible: boolean; selectedRowKeys: Array<Record<string, number>> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const confirmLoading = ref(false);
        // 类型
        const websiteType = ref<1 | 2 | 3>(1);
        const websiteTypeSelectOptions: SelectOption = [
            {
                value: 1,
                label: "排名词"
            },
            {
                value: 2,
                label: "TKD和栏目"
            },
            {
                value: 3,
                label: "自定义词分类"
            }
        ];
        // 确定提交
        const onOkFunc = () => {
            const webid = Object.values(props.selectedRowKeys[0])[0];
            // 调用接口
            confirmLoading.value = true;
            const conditionObj: GenerateTargetKeywordsPost["condition"] = {};
            otherConditionKeys.value.forEach((key) => {
                // @ts-ignore
                conditionObj[key] = otherConditionValues.value[key];
            });
            GenerateTargetKeywordsApi({
                webid,
                max_num: maxNum.value,
                type: websiteType.value,
                engines: enginesType.value,
                condition: conditionObj,
                keyword_type: keywordType.value
            })
                .then((res) => {
                    if (res.data.code === 200) {
                        const blob = new Blob([res.data.data.join("\n")], { type: "text/plain" });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement("a");
                        a.download = +new Date() + ".txt";
                        a.href = url;
                        a.click();
                        URL.revokeObjectURL(url);
                    } else {
                        message.error(res.data.msg || "操作失败!");
                    }
                })
                .catch((e) => {
                    message.error(e.msg);
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        // engines 类型
        const enginesTypeSelectOptions: SelectOption = [
            {
                label: "搜狗",
                value: "搜狗"
            },
            {
                label: "百度",
                value: "百度"
            }
        ];
        // 其他条件
        const otherConditionSelectOptions: SelectOption = [
            {
                label: "百度可排名",
                value: "baidu"
            },
            {
                label: "搜狗可排名",
                value: "sogou"
            },
            {
                label: "网站使用数",
                value: "webuse"
            },
            {
                label: "关键词等级",
                value: "level"
            },
            {
                label: "关键词字数",
                value: "keyword"
            },
            {
                label: "使用分类",
                value: "use_category"
            }
        ];
        const otherConditionKeys = ref<Array<string>>([]);
        const otherConditionValues = ref({
            baidu: 0,
            sogou: 0,
            webuse: { uid: 34, value: 5 },
            keyword: {
                value: 5,
                mode: "lte"
            },
            level: [1],
            use_category: 4
        });
        const otherConditionStyle = { marginTop: "5px" };
        // 引擎
        const enginesType = ref("百度");
        // 最大目标关键词数
        const maxNum = ref(1000);
        // 关键词等级
        const keywordLevelSelectOptions: SelectOption = [
            {
                label: "1级",
                value: 1
            },
            {
                label: "2级",
                value: 2
            },
            {
                label: "3级",
                value: 3
            },
            {
                label: "4级",
                value: 4
            },
            {
                label: "5级",
                value: 5
            }
        ];
        // 关键词长度
        const keywordLengthSelectOptions: SelectOption = [
            { label: "大于等于", value: "gte" },
            { label: "小于等于", value: "lte" },
            { label: "等于", value: "dy" }
        ];
        // 内容人
        const contentPersonSelectOptions: SelectOption = [
            { label: "包梦哲", value: 15 },
            { label: "刘子洋", value: 16 },
            { label: "钱慧敏", value: 34 },
            { label: "董红荣", value: 27 },
            { label: "张林", value: 12 },
            { label: "余梦女", value: 10 }
        ];
        const keywordUseCategorySelectOptions = ref<SelectOption>([]);
        // 使用分类
        const getKeywordUseCategorys = () => {
            getKeywordUseCategorysApi().then((res) => {
                keywordUseCategorySelectOptions.value = res.data.data.map((item: any) => ({ label: item.name, value: item.id }));
            });
        };
        // 自定义分类id
        const keywordType = ref(0);
        onMounted(() => {
            getKeywordUseCategorys();
        });
        return () => (
            <Modal
                v-model:open={visible.value}
                title="生成目标关键词"
                style="width:500px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                <div>
                    <Space>
                        关键词对象
                        <RadioGroup v-model:value={websiteType.value} options={websiteTypeSelectOptions} />
                    </Space>
                </div>
                {websiteType.value === 3 && (
                    <div>
                        <Space>
                            关键词分类
                            <InputNumber placeholder="请输入分类 逗号(,)隔开" v-model:value={keywordType.value}></InputNumber>
                        </Space>
                    </div>
                )}
                {websiteType.value === 1 && (
                    <div style={otherConditionStyle}>
                        <Space>
                            排名任务类型
                            <RadioGroup v-model:value={enginesType.value} options={enginesTypeSelectOptions} />
                        </Space>
                    </div>
                )}
                <Space style={otherConditionStyle}>
                    目标关键词数量
                    <InputNumber placeholder="生成目标关键词数量" v-model:value={maxNum.value}></InputNumber>
                </Space>
                <Divider>过滤条件</Divider>
                <CheckboxGroup
                    v-model:value={otherConditionKeys.value}
                    options={otherConditionSelectOptions}
                    style="width: 100%"
                ></CheckboxGroup>
                {otherConditionKeys.value.includes("baidu") && (
                    <div style={otherConditionStyle}>
                        <Space>
                            百度可排名(大于)
                            <InputNumber v-model:value={otherConditionValues.value.baidu}></InputNumber>
                        </Space>
                    </div>
                )}
                {otherConditionKeys.value.includes("sogou") && (
                    <div style={otherConditionStyle}>
                        <Space>
                            搜狗可排名(大于)
                            <InputNumber v-model:value={otherConditionValues.value.sogou}></InputNumber>
                        </Space>
                    </div>
                )}
                {otherConditionKeys.value.includes("webuse") && (
                    <div style={otherConditionStyle}>
                        <Space>
                            网站使用数(小于)<InputNumber v-model:value={otherConditionValues.value.webuse.value}></InputNumber>
                            内容人
                            <Select
                                options={contentPersonSelectOptions}
                                v-model:value={otherConditionValues.value.webuse.uid}
                            ></Select>
                        </Space>
                    </div>
                )}
                {otherConditionKeys.value.includes("keyword") && (
                    <div style={otherConditionStyle}>
                        <Space>
                            关键词长度
                            <Select
                                options={keywordLengthSelectOptions}
                                v-model:value={otherConditionValues.value.keyword.mode}
                            ></Select>
                            <InputNumber v-model:value={otherConditionValues.value.keyword.value}></InputNumber>
                        </Space>
                    </div>
                )}
                {otherConditionKeys.value.includes("level") && (
                    <div style={otherConditionStyle}>
                        <Space>
                            关键词等级
                            <CheckboxGroup
                                v-model:value={otherConditionValues.value.level}
                                options={keywordLevelSelectOptions}
                            ></CheckboxGroup>
                        </Space>
                    </div>
                )}
                {otherConditionKeys.value.includes("use_category") && (
                    <div style={otherConditionStyle}>
                        <Space>
                            使用分类
                            <Select
                                style="width:120px"
                                v-model:value={otherConditionValues.value.use_category}
                                options={keywordUseCategorySelectOptions.value}
                            ></Select>
                        </Space>
                    </div>
                )}
            </Modal>
        );
    }
});

type WebsiteAddLinkModalContentProps = {
    params: {
        name: string;
        url: string;
        type_id: number;
        pc_domain: string;
        prefix: string;
    };
};
type DestoonCategoryOption = { value: number; label: string; children: Array<DestoonCategoryOption> };
export const WebsiteAddLinkModalContent = defineComponent({
    props: ["params"],
    setup(props: WebsiteAddLinkModalContentProps) {
        const destoonCategoryOptions = ref<Array<DestoonCategoryOption>>([]);
        const selectedCategorys = ref<number>();
        const getDestoonCategory = () => {
            if (props.params.type_id >= 0) {
                getDestoonCategoryApi(props.params.pc_domain)
                    .then((res) => {
                        const arr2 = res.data.data.link_type as Array<{ parentid: string; typeid: string; typename: string }>;
                        arr2.filter((item1) => {
                            if (Number(item1.parentid) === 0) {
                                destoonCategoryOptions.value.push({
                                    value: Number(item1.typeid),
                                    label: item1.typename,
                                    children: []
                                });
                                return false;
                            }
                            return true;
                        }).forEach((item1) => {
                            formatCategory(destoonCategoryOptions.value, item1);
                        });
                    })
                    .catch(() => {
                        message.error("获取destoon分类失败!");
                    });
            }
        };
        watch(destoonCategoryOptions, () => {});
        const formatCategory = (
            arr: Array<DestoonCategoryOption>,
            item1: { parentid: string; typeid: string; typename: string }
        ) => {
            for (const item of arr) {
                if (item.value === Number(item1.parentid)) {
                    item.children.push({ value: Number(item1.typeid), label: item1.typename, children: [] });
                } else if (item.children) {
                    formatCategory(item.children, item1);
                }
            }
        };
        watch(
            () => selectedCategorys.value,
            (v) => {
                props.params.type_id = selectedCategorys.value as number;
            }
        );
        const slots = {
            addonBefore: () => (
                <Select v-model:value={props.params.prefix} style="width: 90px">
                    <SelectOption value="http://">http://</SelectOption>
                    <SelectOption value="https://">https://</SelectOption>
                </Select>
            )
        };
        getDestoonCategory();
        return () => (
            <>
                <br />
                <Space>
                    网站地址<Input placeholder="url地址" v-model:value={props.params.url}></Input>
                </Space>
                <br />
                <br />
                <Space>
                    友链名称<Input placeholder="友链名称" v-model:value={props.params.name}></Input>
                </Space>
                <div v-show={props.params.type_id >= 0}>
                    <br />
                    <Space>
                        分类
                        <TreeSelect
                            v-model:value={selectedCategorys.value}
                            show-search
                            allow-clear
                            style="width:200px"
                            show-checked-strategy="SHOW_ALL"
                            tree-default-expand-all
                            tree-data={destoonCategoryOptions.value}
                            tree-node-filter-prop="label"
                        ></TreeSelect>
                    </Space>
                </div>
            </>
        );
    }
});

type DomainInfoShowFieldsModalProps = {
    showFields: Array<string>;
    fieldOptionsGroupObj: FieldOptionsObjType;
    visible: boolean;
};
export const DomainInfoShowFieldsModal = defineComponent({
    props: ["showFields", "fieldOptionsGroupObj", "visible"],
    emit: ["update:showFields", "update:visible"],
    setup(props: DomainInfoShowFieldsModalProps, { emit }) {
        const { showFields, visible } = useVModels(props, emit);
        const inputValue = ref("");
        const fieldOptionsGroupObj = computed(() => {
            return props.fieldOptionsGroupObj;
            // if (!inputValue.value) return props.fieldOptions;
            // return props.fieldOptions.filter((item) => item.label.includes(inputValue.value));
        });
        const onChange = (item:FieldOptionsObjType[string])=>{
            if(item.checkAll){
                item.options
            }

        }
        return () => (
            <Modal
                v-model:open={visible.value}
                footer={false}
                title="请选择字段"
                onOk={() => (visible.value = false)}
                style="width:900px"
            >
                <CheckboxGroup style="width:100%" v-model:value={showFields.value}>
                    <div style="width:100%;">
                        {Object.keys(fieldOptionsGroupObj.value).map((key) => {
                            const item = fieldOptionsGroupObj.value[key]
                            return (
                                <Row>
                                    <h3 style="width:100%;font-weight: bold;padding: 10px 0;">{key}</h3>
                                    {item.options.map((item) => {
                                        return (
                                            <>
                                                <Checkbox value={item.value} style="margin-right:10px">
                                                    {item.label}
                                                </Checkbox>
                                            </>
                                        );
                                    })}
                                </Row>
                            );
                        })}
                    </div>
                </CheckboxGroup>
            </Modal>
        );
    }
});

export const LinkSystemControlComponent = defineComponent({
    props: ["row"],
    setup(props: { row: Record<string, any> }) {
        // 推送友链
        const pushLinkFunc = () => {
            pushWebsiteLinkApi(props.row.record.pc_domain)
                .then(() => {
                    message.success("操作成功!");
                })
                .catch((e) => {
                    message.error(e.response.data.msg);
                });
        };
        const linkCheck = () => {
            websiteLinkCheckApi(props.row.record.pc_domain)
                .then(() => {
                    message.success("操作成功!");
                })
                .catch((e) => {
                    message.error(e.response.data.msg);
                });
        };
        const toLinks = () => {
            window.open(
                toUrl(`/friendly-chain-system/website?pc_domain=${props.row.record.pc_domain}`),
                "_blank"
            );
        };
        const slots = {
            overlay: () => (
                <Menu>
                    <MenuItem onClick={toLinks}>友链列表</MenuItem>
                    <MenuItem onClick={pushLinkFunc}>推送友链</MenuItem>
                    <MenuItem onClick={linkCheck}>友链检查</MenuItem>
                </Menu>
            )
        };
        return () => (
            <Dropdown v-slots={slots}>
                <a>
                    友链操作
                    <DownOutlined />
                </a>
            </Dropdown>
        );
    }
});

const exportHandleType = [
    { label: "根据选中项", value: 1 },
    { label: "根据搜索结果", value: 2 }
];

type ExportDataHandleComponentProps = {
    visible: boolean;
    fields: Array<string>;
    esIds: Array<number>;
    esQuery: Record<string, any>;
    fieldOptions: SelectOption;
};
// 导出数据
export const ExportDataHandleComponent = defineComponent({
    props: ["visible", "fields", "esIds", "esQuery", "fieldOptions"],
    emits: ["update:visible"],
    setup(props: ExportDataHandleComponentProps, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const exportFunc = () => {
            if (!props.esIds.length && exportType.value === 1) {
                message.error("最少选中一项!");
                return;
            }
            if (!exportFields.value.length) {
                message.error("选择字段!!");
                return;
            }
            getDomainSelectInfoApi().then((res) => {
                if (res.data.code === 200) {
                    const presetData:Record<string,any> = {}
                    res.data.data.forEach((item: any) => {
                        presetData[item.fileds] = item["data"].reduce((p:Record<string,any>,c:{name:string,id:number})=>{
                            p[c.id] = c.name
                            return p
                        },{})
                    });
                    btnLoading.value = true;
                    esCommonActionApi("post", {
                        host: "http://192.168.1.90:9200",
                        index: "websites",
                        ids: props.esIds,
                        idField:"id",
                        query: props.esQuery,
                        type: exportType.value,
                        fields: exportFields.value,
                        presetData,
                    })
                        .then((res) => {
                            if (res.data.code === 200) {
                                window.open(import.meta.env.VITE_QZ_API_URL + res.data.url);
                                message.success("操作成功!");
                            } else {
                                message.error("操作失败!");
                            }
                        })
                        .finally(() => {
                            btnLoading.value = false;
                            visible.value = false;
                        });
                }
            });
        };
        const exportFields = ref<Array<string>>([]);
        const exportType = ref<1 | 2>(1);
        const btnLoading = ref(false);
        return () => (
            <Modal v-model:open={visible.value} title="导出操作" onOk={exportFunc} okButtonProps={{ loading: btnLoading.value }}>
                <RadioGroup v-model:value={exportType.value} options={exportHandleType}></RadioGroup>
                <Divider>选择导出的字段(字段必须已再表中显示)</Divider>
                <CheckboxGroup options={props.fieldOptions} v-model:value={exportFields.value}></CheckboxGroup>
            </Modal>
        );
    }
});

type OtherConditionComponentProps = {
    visible: boolean;
    conditions: Array<{
        field: string;
        value: string;
        type: number;
    }>;
};
// 其他条件
export const OtherConditionComponent = defineComponent({
    props: ["visible", "conditions"],
    emits: ["update:visible", "update:conditions"],
    setup(props: OtherConditionComponentProps, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const conditions = useVModel(props, "conditions", emit);

        const fieldOptions: SelectOption = [
            {
                label: "请选择",
                value: ""
            },
            {
                label: "新百度",
                value: "new_baidu"
            },
            {
                label: "新百核",
                value: "new_baidu_core"
            },
            {
                label: "百度蜘蛛",
                value: "baidu_spider_total"
            },
            {
                label: "新搜狗",
                value: "new_sogou"
            },
            {
                label: "新搜核",
                value: "new_sogou_core"
            },
            {
                label: "百收",
                value: "baidu_soulu"
            },
            {
                label: "搜收",
                value: "sogou_soulu"
            },
            {
                label: "友链数",
                value: "link_num"
            },
            {
                label: "总文章数",
                value: "article_sum"
            },
            {
                label: "访问数",
                value: "visit_num"
            },
            {
                label: "触发数",
                value: "trigger_num"
            },
            {
                label: "搜索引擎来源访问数",
                value: "search_engine_referrer_visit_num"
            }
        ];
        const fieldMap = (()=>{
            const obj:Record<string,any> = {}
            for(const item of fieldOptions){
                obj[item["value"]] = item["label"]
            }
            return obj
        })()
        const currentField = ref("");
        const addCondition = () => {
            if (!currentField.value) {
                message.error("请选择字段!");
                return;
            }
            conditions.value.push({ value: "", field: currentField.value, type: -1 });
        };
        const removeCondition = (index: number) => {
            conditions.value.splice(index, 1);
        };
        return () => (
            <Modal v-model:open={visible.value} title="添加其他搜索条件" style="width:460px" onOk={() => (visible.value = false)}>
                {conditions.value.map((item, index) => {
                    return (
                        <div style="display:flex;margin-top:10px;align-items:center">
                            <span style="width:150px">{fieldMap[item.field]}</span>
                            <InputNumber style="width:100px" v-model:value={item.value}></InputNumber>
                            <Select style="margin:0 20px;width:80px" v-model:value={item.type}>
                                <a-select-option value={0}>等于</a-select-option>
                                <a-select-option value={-1}>小于</a-select-option>
                                <a-select-option value={1}>大于</a-select-option>
                            </Select>
                            <MinusCircleOutlined
                                class="delete-button"
                                style="font-size:24px;color:#ff0000ab;"
                                onClick={() => removeCondition(index)}
                            />
                        </div>
                    );
                })}
                <div style="display:flex;margin-top:20px">
                    <Select
                        style="width:30%;margin-right:10px"
                        options={fieldOptions}
                        v-model:value={currentField.value}
                        show-search
                        filter-option={filterOption}
                    ></Select>
                    <Button type="dashed" style="width: 70%" onClick={() => addCondition()}>
                        <PlusOutlined />
                        添加项
                    </Button>
                </div>
            </Modal>
        );
    }
});
export const SingleWebRankingAnalysisUpsAndDownsComponent =  defineComponent({
    props: ["visible", "ids"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; ids: number[]}, { emit }) {
        const visible = useVModel(props, "visible", emit);
        // 确定后加载的按钮
        const confirmLoading = ref(false);
        const preRedisKey = ref("");
        const nextRedisKey = ref("");
        const onOkFunc = () => {
            confirmLoading.value = true
            singleWebRankingkeywordAnalysisUpsAndDownsApi({
                pre_redis_key: preRedisKey.value,
                current_redis_key: nextRedisKey.value,
                id: props.ids[0],
                field:"webid",
            })
                .then((res) => {
                    message.success("准备下载Excel文件...");
                    window.open(import.meta.env.VITE_QZ_API_URL + res.data.csv_file_path,"_blank")
                })
                .catch((e) => {
                    message.error("服务器错误!");
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        const redisOptions = ref([]);
        onMounted(() => {
            keywordRankingTaskRedisKeysApi().then((res) => {
                redisOptions.value = res.data.data;
            });
        });
        return () => (
            <Modal
                v-model:open={visible.value}
                title="选择最近两次排名结果"
                style="width:460px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                前一次：
                <Select
                    v-model:value={preRedisKey.value}
                    filter-option={filterOption}
                    showSearch
                    style={{ width: "100%" }}
                    options={redisOptions.value}
                ></Select>
                后一次：
                <Select
                    v-model:value={nextRedisKey.value}
                    filter-option={filterOption}
                    style={{ width: "100%" }}
                    showSearch
                    options={redisOptions.value}
                ></Select>
            </Modal>
        );
    }
});

export const RankingAnalysisUpsAndDownsComponent = defineComponent({
    props: ["visible", "esIds", "esQuery"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[]; esQuery: Record<string, any> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        // 确定后加载的按钮
        const confirmLoading = ref(false);
        const preRedisKey = ref("");
        const nextRedisKey = ref("");
        const onOkFunc = () => {
            confirmLoading.value = true
            keywordRankingAnalysisUpsAndDownsApi({
                pre_redis_key: preRedisKey.value,
                next_redis_key: nextRedisKey.value,
                ids: props.esIds,
                es_query: props.esQuery
            })
                .then((res) => {
                    message.success("准备下载Excel文件...");
                    window.location.href = import.meta.env.VITE_QZ_API_URL + res.data.csv_file_path;
                })
                .catch((e) => {
                    message.error("服务器错误!");
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        const redisOptions = ref([]);
        onMounted(() => {
            keywordRankingTaskRedisKeysApi().then((res) => {
                redisOptions.value = res.data.data;
            });
        });
        return () => (
            <Modal
                v-model:open={visible.value}
                title="选择最近两次排名结果"
                style="width:460px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                前一次：
                <Select
                    v-model:value={preRedisKey.value}
                    filter-option={filterOption}
                    showSearch
                    style={{ width: "100%" }}
                    options={redisOptions.value}
                ></Select>
                后一次：
                <Select
                    v-model:value={nextRedisKey.value}
                    filter-option={filterOption}
                    style={{ width: "100%" }}
                    showSearch
                    options={redisOptions.value}
                ></Select>
            </Modal>
        );
    }
});
export const WebsiteRankingAnalysisComponent = defineComponent({
    props: ["visible", "esIds", "esQuery"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[]; esQuery: Record<string, any> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        // 确定后加载的按钮
        const confirmLoading = ref(false);
        const preRedisKey = ref("");
        const nextRedisKey = ref("");
        const onOkFunc = () => {
            WebsiteRankingAnalysisReportApi({
                pre_redis_key: preRedisKey.value,
                next_redis_key: nextRedisKey.value,
                ids: props.esIds,
                es_query: props.esQuery
            })
                .then((res) => {
                    message.success("准备下载Excel文件...");
                    window.location.href = import.meta.env.VITE_QZ_API_URL + res.data.csv_file_path;
                })
                .catch((e) => {
                    message.error("服务器错误!");
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        const redisOptions = ref([]);
        onMounted(() => {
            keywordRankingTaskRedisKeysApi().then((res) => {
                redisOptions.value = res.data.data;
            });
        });
        return () => (
            <Modal
                v-model:open={visible.value}
                title="选择最近两次排名结果"
                style="width:460px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                前一次：
                <Select
                    v-model:value={preRedisKey.value}
                    filter-option={filterOption}
                    showSearch
                    style={{ width: "100%" }}
                    options={redisOptions.value}
                ></Select>
                后一次：
                <Select
                    v-model:value={nextRedisKey.value}
                    filter-option={filterOption}
                    style={{ width: "100%" }}
                    showSearch
                    options={redisOptions.value}
                ></Select>
            </Modal>
        );
    }
});
export const WebRankContinedUpOrDownAnalysisComponent = defineComponent({
    props: ["visible", "esIds", "esQuery"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[]; esQuery: Record<string, any> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        // 确定后加载的按钮
        const confirmLoading = ref(false);
        const thesaurus = ref(0);
        
        const onOkFunc = () => {
            if(!thesaurus.value){
                return message.error("请选择词库项目!")
            }
            webrankContinuedDownOrUpAnalysisApi({
                last_num: lastNum.value,
                thesaurus_id: thesaurus.value,
                ids: props.esIds,
                es_query: props.esQuery
            })
                .then((res) => {
                    message.success("准备下载Excel文件...");
                    window.location.href = import.meta.env.VITE_QZ_API_URL + res.data.csv_file_path;
                })
                .catch((e) => {
                    message.error("服务器错误!");
                })
                .finally(() => {
                    confirmLoading.value = false;
                    visible.value = false;
                });
        };
        const thesaurusOptions = ref([]);
        onMounted(() => {
            keywordThesaurusApi().then((res) => {
                thesaurusOptions.value = res.data.data.map((item:any) => ({ label: item.name, value: item.id }));
            });
        });
        const lastNum = ref(7);
        return () => (
            <Modal
                v-model:open={visible.value}
                title="选择最近两次排名结果"
                style="width:360px"
                onOk={onOkFunc}
                confirmLoading={confirmLoading.value}
                onCancel={() => (visible.value = false)}
            >
                <br/>
                <Space>
                最近几次排名：<InputNumber v-model:value={lastNum.value}></InputNumber>
                </Space>
                <div></div>
                <br/>
                <Space>
                词库项目：
                <Select
                    v-model:value={thesaurus.value}
                    filter-option={filterOption}
                    style={{ width: "150px" }}
                    showSearch
                    options={thesaurusOptions.value}
                ></Select>
                </Space>
                <div></div>
                <br/>
            </Modal>
        );
    }
});
export const WebsiteBulkBindAdvertiserComponent = defineComponent({
    props: ["visible", "esIds"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[] }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const alertShow = inject("alertShow", ref(false));
        const alertDescription = inject("alertDescription", ref(""));
        const isCover = ref(false);
        const options = [
            {
                label: "PC",
                value: "pc"
            },
            {
                label: "M",
                value: "m"
            }
        ];
        const type = ref("pc");
        const adId = ref();
        const { adOptions, adVarIdMap } = useAdOptions();
        const { filterOption } = useCommonStaticOptions();
        const { varMap } = useVarOptions();
        const varValueList = ref<Array<{ label: string; value: string; field: string }>>([]);
        watch(adId, () => {
            varValueList.value = (adVarIdMap.value[adId.value] || []).map((varId) => {
                return { label: varMap.value[varId].alias, value: "", field: varMap.value[varId].name };
            });
        });
        const computedAdOptions = computed(() => {
            return adOptions.value?.filter((item) => {
                console.log(item.label);
                if (type.value == "pc") {
                    return item.label.includes("pc") || item.label.includes("PC") || item.label.includes("自适应");
                }
                if (type.value == "m") {
                    return item.label.includes("m端") || item.label.includes("移动");
                }
                return true;
            });
        });
        watch(type, () => {
            adId.value = 0;
        });
        const onOk = () => {
            const varValueMap: Record<string, string> = {};
            for (const item of varValueList.value) {
                item.value = item.value.trim();
                if (item.value == "") {
                    return message.error("变量值不能为空!");
                }
                varValueMap[item.field] = item.value;
            }
            btnLoading.value = true;
            const params = {
                pc_var_value_map: {},
                m_var_value_map: {},
                m_ad_id: -1,
                pc_ad_id: -1,
                ids: props.esIds,
                is_cover: isCover.value
            };
            if (type.value == "pc") {
                params.pc_ad_id = adId.value;
                params.pc_var_value_map = varValueMap;
            } else {
                params.m_ad_id = adId.value;
                params.m_var_value_map = varValueMap;
            }
            websiteAndAdApi("post", params, $store.userInfo.id)
                .then((res) => {
                    message.success(res.data.msg || "添加成功!!!");
                })
                .catch((e) => {
                    alertShow.value = true;
                    alertDescription.value = e.response.data.msg;
                })
                .finally(() => {
                    visible.value = false;
                    btnLoading.value = false;
                });
        };
        const btnLoading = ref(false);
        return () => (
            <Modal
                v-model:open={visible.value}
                onOk={onOk}
                style="width:450px"
                title="批量绑定广告"
                okButtonProps={{ loading: btnLoading.value }}
            >
                <Space>
                    如果网站已有广告，是否覆盖：<Switch v-model:checked={isCover.value}></Switch>
                </Space>
                <br />
                <br />
                目标位置：<RadioGroup optionType="button" options={options} v-model:value={type.value}></RadioGroup>
                <br />
                <br />
                选择广告：
                <Select
                    style="width:250px"
                    v-model:value={adId.value}
                    filter-option={filterOption}
                    showSearch
                    options={computedAdOptions.value}
                ></Select>
                <Divider>广告变量</Divider>
                {varValueList.value.map((item, index) => {
                    return (
                        <>
                            {item.label}：
                            <AutoComplete
                                style="width:100%"
                                v-model:value={item.value}
                                options={useVarValueOptions(item.field).value}
                            >
                                <Input v-model:value={item.value}></Input>
                            </AutoComplete>
                        </>
                    );
                })}
            </Modal>
        );
    }
});
export const BulkBindSecurityConfigComponent = defineComponent({
    props: ["visible", "esIds"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[] }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const alertShow = inject("alertShow", ref(false));
        const alertDescription = inject("alertDescription", ref(""));
        const configId = ref(0);
        const webSecurityConfigOptions = useWebSecurityConfigOptions();
        const { filterOption } = useCommonStaticOptions();
        
        const onOk = () => {
            btnLoading.value = true;
            const params = {
                ids: props.esIds,
                config_id:configId.value,
                config_name:webSecurityConfigOptions.value.find(item=>item.value == configId.value)?.label,
            };
            if(!params.config_id){
                message.error("请选择配置id!")
                return
            }
            webBindSecurityConfigApi("post", params)
                .then((res) => {
                    message.success(res.data.msg || "添加成功!!!");
                })
                .catch((e) => {
                    if(!e.response.data.msg){
                        return message.error("服务器错误!")
                    }
                    alertShow.value = true;
                    alertDescription.value = e.response.data.msg;
                    console.log("测试")
                })
                .finally(() => {
                    visible.value = false;
                    btnLoading.value = false;
                });
        };
        const btnLoading = ref(false);
        return () => (
            <Modal
                v-model:open={visible.value}
                onOk={onOk}
                style="width:450px"
                title="批量绑定网站安全策略"
                okButtonProps={{ loading: btnLoading.value }}
            >
                如果网站已有配置，会覆盖!
                <br />
                <br />
                选择安全配置：
                <Select
                    style="width:250px"
                    v-model:value={configId.value}
                    filter-option={filterOption}
                    showSearch
                    options={webSecurityConfigOptions.value}
                ></Select>
            </Modal>
        );
    }
})
export const BulkBindDynamicLinkConfigComponent = defineComponent({
    props: ["visible", "esIds","rows"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[],rows:Array<Record<string,any>> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const alertShow = inject("alertShow", ref(false));
        const alertDescription = inject("alertDescription", ref(""));
        const webLinkRuleOptions = useWebLinkRuleOptions();
        const { filterOption } = useCommonStaticOptions();
        const onOk = () => {
            if(!params.rule_id){
                return message.error("请选择规则!")
            }
            params.program_type = props.rows[0]['program_type']
            btnLoading.value = true;
            const domains = props.rows.map(item=>{
                if(params.type == 1){
                    return item['pc_domain']
                }else if(item['m_domain'] && params.type == 2 ){
                    return item['m_domain']
                }else{
                    return undefined
                }
            }).filter(Boolean)
            websiteDynamicOutlinkConfigApi("post", {domains,...params})
                .then((res) => {
                    message.success(res.data.msg || "添加成功!!!");
                })
                .catch((e) => {
                    if(!e.response.data.msg){
                        return message.error("服务器错误!")
                    }
                    alertShow.value = true;
                    alertDescription.value = e.response.data.msg;
                })
                .finally(() => {
                    visible.value = false;
                    btnLoading.value = false;
                });
        };
        const params = reactive({
            rule_id:0,
            show_num:10,
            type:1,
            mode:1,
            view_type:1,
            program_type:0
        })
        const btnLoading = ref(false);
        return () => (
            <Modal
                v-model:open={visible.value}
                onOk={onOk}
                style="width:500px"
                title="批量绑定网站动态外链规则"
                okButtonProps={{ loading: btnLoading.value }}
            >
                <br/>
                <Space size="middle" direction="vertical">
                <div>

                模式：
                <RadioGroup  v-model:value={params.mode} optionType="button">
                    <Radio value={1}>覆盖</Radio>
                    <Radio value={2}>追加</Radio>
                    <Radio value={3}>删除</Radio>
                </RadioGroup>
                </div>
                <div>
                类型：
                <RadioGroup v-model:value={params.type} optionType="button">
                    <Radio value={1}>PC</Radio>
                    <Radio value={2}>M</Radio>
                </RadioGroup>
                </div>
                <div>
                外链位置：
                <RadioGroup v-model:value={params.view_type} optionType="button">
                    <Radio value={1}>首页</Radio>
                    <Radio value={2}>栏目页</Radio>
                    <Radio value={3}>文章页</Radio>
                </RadioGroup>
                </div>
                <div>
                    外链规则：
                    <Select
                        style="width:200px;margin-right:5px;"
                        v-model:value={params.rule_id}
                        filter-option={filterOption}
                        showSearch
                        options={webLinkRuleOptions.value}
                    ></Select>
                </div>
                <div style="display:flex;align-items:center">
                调用条数：
                <InputNumber v-model:value={params.show_num}></InputNumber>
                </div>
                </Space>
            </Modal>
        );
    }
})
export const WebsiteBulkUpdateTplComponent = defineComponent({
    props: ["visible", "esIds", "program_id"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[]; program_id: number }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const alertShow = inject("alertShow", ref(false));
        const alertDescription = inject("alertDescription", ref(""));
        const options = [
            {
                label: "PC",
                value: "pc"
            },
            {
                label: "M",
                value: "m"
            }
        ];
        const type = ref<"pc" | "m">("pc");
        const { filterOption } = useCommonStaticOptions();
        const computedTplOptions = computed(() =>
            tplMap.value[type.value].filter((v) => {
                return programMap[v.type].includes(props.program_id);
            })
        );
        const tplMap = ref<{ m: Array<SelectOption & { type: number }>; pc: Array<SelectOption & { type: number }> }>({
            m: [],
            pc: []
        });
        // 运维端与运营端程序ID映射
        const programMap: Record<number, Array<number>> = {
            1: [1],
            5: [5],
            10: [10],
            11: [11],
            12: [12],
            14: [14],
            15: [15],
            16: [16],
            17: [17],
            18: [18],
            19: [19, 20, 22],
            20: [21],
            21: [23],
            22: [24],
            24: [26],
        };
        const getTplList = () => {
            getWebsiteTplListApi().then((res) => {
                // @ts-ignore
                tplMap.value.m = res.data.data["m"]
                    .filter((v) => v.program_id)
                    .map((item: any) => ({
                        value: item.id,
                        label: item.name,
                        type: item.program_id
                    }));
                // @ts-ignore
                tplMap.value.pc = res.data.data["pc"]
                    .filter((v) => v.program_id)
                    .map((item: any) => ({
                        value: item.id,
                        label: item.name,
                        type: item.program_id
                    }));
            });
        };
        const tplId = ref(0);
        const onOk = () => {
            btnLoading.value = true;
            const params = {
                tpl_id: tplId.value,
                tpl_type: type.value,
                ids: props.esIds
            };
            updateWebsiteTplApi(params)
                .then((res) => {
                    message.success(res.data.msg || "添加成功!!!");
                })
                .catch((e) => {
                    alertShow.value = true;
                    alertDescription.value = e.response.data.msg;
                })
                .finally(() => {
                    visible.value = false;
                    btnLoading.value = false;
                });
        };
        const btnLoading = ref(false);
        onMounted(() => {
            getTplList();
        });
        watch(type, () => {
            tplId.value = 0;
        });
        watch(
            () => props.program_id,
            (v) => {
                tplId.value = 0;
            }
        );
        return () => (
            <Modal
                v-model:open={visible.value}
                onOk={onOk}
                style="width:450px"
                title="批量更新模版"
                okButtonProps={{ loading: btnLoading.value }}
            >
                目标位置：<RadioGroup optionType="button" options={options} v-model:value={type.value}></RadioGroup>
                <br />
                <br />
                选择模版：
                <Select
                    style="width:250px"
                    v-model:value={tplId.value}
                    filter-option={filterOption}
                    showSearch
                    options={computedTplOptions.value}
                ></Select>
            </Modal>
        );
    }
});

export const WebsiteBulkUpdateWebsiteProgramComponent = defineComponent({
    props: ["visible", "rows"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; rows: Array<Record<string,any>> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const webProgramId = ref(0)
        const { filterOption } = useCommonStaticOptions();
        const options = ref<SelectOption>([])
        const getWebsiteProgramList = () => {
            getWebProgramsApi().then((res) => {
                // @ts-ignore
                options.value = res.data.data.map((item: any) => ({
                        value: item.id,
                        label: item.name,
                    })).concat({label:"请选择",value:0})
            });
        };
        const onOk = () => {
            btnLoading.value = true;
            if(webProgramId.value <= 0){
                message.error("请选择!")
                return
            }
            updateWebProgramIdApi(webProgramId.value,props.rows.map(item=>item.apiv2))
                .then((res) => {
                    message.success(res.data.msg || "添加成功!!!");
                })
                .catch((e) => {
                    message.error("修改失败！");
                })
                .finally(() => {
                    visible.value = false;
                    btnLoading.value = false;
                });
        };
        const btnLoading = ref(false);
        onMounted(() => {
            getWebsiteProgramList();
        });
        
        return () => (
            <Modal
                v-model:open={visible.value}
                onOk={onOk}
                style="width:450px"
                title="批量更新网站程序类型"
                okButtonProps={{ loading: btnLoading.value }}
            >
                
                选择网站程序类型：
                <Select
                    style="width:250px"
                    v-model:value={webProgramId.value}
                    filter-option={filterOption}
                    showSearch
                    options={options.value}
                ></Select>
            </Modal>
        );
    }
});

export const WebsiteBulkUpdateNginxRuleComponent = defineComponent({
    props: ["visible", "rows"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; rows: Array<Record<string,any>> }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const nginxId = ref(0)
        const { filterOption } = useCommonStaticOptions();
        const nginxRuleOptions = ref<SelectOption>([])
        const getNginxRuleList = () => {
            getNginxRuleApi().then((res) => {
                // @ts-ignore
                nginxRuleOptions.value = res.data.data.map((item: any) => ({
                        value: item.id,
                        label: item.name,
                    })).concat({label:"请选择",value:0})
            });
        };
        const onOk = () => {
            btnLoading.value = true;
            if(nginxId.value <= 0){
                message.error("请选择!")
                return
            }
            updateWebsiteNginxRuleIdApi(nginxId.value,props.rows.map(item=>item.apiv2))
                .then((res) => {
                    message.success(res.data.msg || "添加成功!!!");
                })
                .catch((e) => {
                    message.error("修改失败！");
                })
                .finally(() => {
                    visible.value = false;
                    btnLoading.value = false;
                });
        };
        const btnLoading = ref(false);
        onMounted(() => {
            getNginxRuleList();
        });
        
        return () => (
            <Modal
                v-model:open={visible.value}
                onOk={onOk}
                style="width:450px"
                title="批量更新nginx规则"
                okButtonProps={{ loading: btnLoading.value }}
            >
                
                选择Nginx规则：
                <Select
                    style="width:250px"
                    v-model:value={nginxId.value}
                    filter-option={filterOption}
                    showSearch
                    options={nginxRuleOptions.value}
                ></Select>
            </Modal>
        );
    }
});

export const WebsiteBulkSetTplWycComponent = defineComponent({
    props: ["visible", "esIds"],
    emits: ["update:visible"],
    setup(props: { visible: boolean; esIds: number[] }, { emit }) {
        const visible = useVModel(props, "visible", emit);
        const isCover = ref(false);
        const onOk = () => {
            btnLoading.value = true;
            const params = {
                add_class_status: Number(addClass.value),
                add_attr_status: Number(addAttr.value),
                add_other_tag_status: Number(addOtherTag.value),
                ids: props.esIds,
                is_cover: Number(isCover.value)
            };
            websitesBulkBindTplWycApi(params)
                .then((res) => {
                    message.success(res.data.msg || "添加成功!!!");
                })
                .finally(() => {
                    visible.value = false;
                    btnLoading.value = false;
                });
        };
        const btnLoading = ref(false);
        const addClass = ref(true);
        const addAttr = ref(true);
        const addOtherTag = ref(true);
        return () => (
            <Modal
                v-model:open={visible.value}
                onOk={onOk}
                style="width:450px"
                title="设置模版伪原创"
                okButtonProps={{ loading: btnLoading.value }}
            >
                <br />
                <Space>
                    如果网站已配置模版伪原创，是否覆盖：<Switch v-model:checked={isCover.value}></Switch>
                </Space>
                <br />
                <br />
                <Space>
                    随机class：<Switch v-model:checked={addClass.value}></Switch>
                </Space>
                <br />
                <br />
                <Space>
                    随机自定义属性：<Switch v-model:checked={addAttr.value}></Switch>
                </Space>
                <br />
                <br />
                <Space>
                    随机杂乱标签：<Switch v-model:checked={addOtherTag.value}></Switch>
                </Space>
                <br />
            </Modal>
        );
    }
});
export const WebsiteShowDataComponent = defineComponent({
    props: ["visible", "currentRow"],
    setup(props: { visible: boolean; currentRow: Record<string,any> }, { emit }){
        const visible = useVModel(props, "visible", emit);
        const currentRow = computed(()=>props.currentRow)
        const selectData = useDomainSelectData()
        const showDataFieldMap = {
            "web_name":"网站名称",
            "index_title":"首页标题",
            "pc_domain":"Pc域名",
            "m_domain":"M域名",
            "default_keyword":"默认关键词",
            "web_user":"网站组",
            "link_user":"友链人",
            "content_user":"内容人",
            "website_type":"行业类型",
            "websitetype_child":"行业类型子类",
            "program_type":"程序分类",
            "adapt_type":"级别分类",
            "ad_website":"dede插件",
            "jsc_type":"XXF分类",
            "domain_account":"域名账号",
            "dns_account":"DNS账号",
            "guoneiad_type":"国内广告",
            "shipei_type":"适配类型",
            "ad_type":"备用",
            "keywords_type":"关键词类型",
            "content_type":"地区类型",
            "neilian_type":"搜索类型",
            "seo_type":"seo类型",
            "website_group_type":"文章策略",
            "nip":"内网IP",
            "rds_name":"数据库名称",
            "origin_ip":"源站IP",
            "load_balance":"负载均衡IP",
            "cdn_ip":"CDN主IP",
            "qz":"表前缀",
        }
        return ()=>(
            <Modal v-model:open={visible.value} title="网站数据展示"  width="800px">
                <Row gutter={[5,6]}>
                {
                    Object.keys(showDataFieldMap).map(key=>{
                        return (
                            <Col span={12} style={{display:"flex",alignItems:"center",marginBottom:"10px"}}>
                                <span style="width:120px">{showDataFieldMap[key]}</span>
                                <Input value={selectData.value[key] ? selectData.value[key][currentRow.value[key]] : currentRow.value[key]  } />
                            </Col>
                        )
                    })
                }
                </Row>
                
        </Modal>
        )
    }
})
export const WebsiteDynamicAdComponent = defineComponent({
    props: ["visible", "rows"],
    setup(props: { visible: boolean; rows: Record<string,any> }, { emit }){
        const visible = useVModel(props, "visible", emit);
        const defaultUserAgents = ["bytedancewebview", "baiduboxapp"]
const defaultReferers = ['baidu.com', 'google.com',
    'google.cn',
    'sogou.com',
    'so.com',
    'douyin.com',
    'bing.com',
    'yahoo.com',
    'yandex.ru',
    'toutiao.com',
    'zhihu.com',
    'weibo.com',
    'yandex.eu',
    'quark.cn',
    'weibo.cn',
    'twitter.com',
    'facebook.com',
    'duckduckgo.com',
    '360.cn',
    'sm.cn']
    const $store = mainStore();
let { id: uid } = $store.userInfo;
        const params= reactive({
            type:1,
            domains: [] as string[],
            err_html: '',
            user_agents: defaultUserAgents,
            referers: defaultReferers,
            ad_name: [],
            uid,
            comment: ''
        })
        const add = ()=>{
            params.domains = props.rows.map(item=>{
                if(params.type == 1){
                    return item['pc_domain']
                }else if(item['m_domain'] && params.type == 2 ){
                    return item['m_domain']
                }else{
                    return undefined
                }
            }).filter(Boolean)
            if(params.domains.length == 0){
                return message.error("请选择域名!")
            }
            addWebsiteDynamicAdApi(params).then(res=>{
                message.success("添加成功!")
            }).catch(e=>{
                message.error("添加失败!")
            }).finally(()=>{
                visible.value = false
            })
        }
        return ()=>(
            <Modal onOk={add} v-model:open={visible.value} title="绑定动态广告" width="800px">

            
            <Space direction="vertical">
            <TypographyParagraph>
            <blockquote>如果是蜘蛛访问，则返回网站源码。</blockquote>
            <blockquote>如果用户访问符合指定来源和ua 则返回广告，否则返回错误HTML。</blockquote>
            </TypographyParagraph>
            <div>
            类型：
                <RadioGroup v-model:value={params.type} optionType="button">
                    <Radio value={1}>PC</Radio>
                    <Radio value={2}>M</Radio>
                </RadioGroup>
            </div>
            <div>
            错误HTML
            <Textarea v-model:value={params.err_html} placeholder="请输入错误HTML" rows={4} />
            </div>
            <div>
            允许的UserAgent
                    <Select style="width:100%" v-model:value={params.user_agents} mode="tags" placeholder="请输入User Agents"
                        token-separators={[',']} />
            </div>
                
            <div>
            允许的Referers
                    <Select style="width:100%" v-model:value={params.referers} mode="tags" placeholder="请输入Referers"
                        token-separators={[',']} />
            </div>
            <div>
                
                    
                    广告名称:
                    <Select style="width:100%" v-model:value={params.ad_name} mode="tags" placeholder="请输入广告名称，多个以逗号分隔"
                        token-separators={[',']} />
            </div>
            <div>

                备注:
                    <Input v-model:value={params.comment} placeholder="请输入备注" />
            </div>
            </Space>
            </Modal>
        )
    }
})